package com.huiyeji.hui.utils;

import com.alibaba.fastjson.JSON;
import com.huiyeji.hui.vo.MessageVo;
import com.huiyeji.hui.ws.ChatEndpoint;

import javax.websocket.EncodeException;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author zhaoduo
 */
public class MessageUtil {

    public static MessageVo buildMessageVo(String message){
        return JSON.parseObject(message,MessageVo.class);
    }

    public static MessageVo buildErrorMessageVo(String msg){
        return new MessageVo(null,null,msg, LocalDateTime.now(), MessageVo.Type.ERROR);
    }

    public static void groupSend(List<Long> receivers,MessageVo vo){
        receivers.forEach(receiver->{
            ChatEndpoint endpoint = ChatEndpoint.ONLINE_USERS.get(receiver);
            if (endpoint != null){
                try {
                    endpoint.send(vo);
                } catch (EncodeException | IOException ignored) {}
            }
        });
    }

    public static void groupSend(List<MessageVo> vos){
        vos.forEach(vo->{
            ChatEndpoint endpoint = ChatEndpoint.ONLINE_USERS.get(vo.getReceiver());
            if (endpoint != null){
                try {
                    endpoint.send(vo);
                } catch (EncodeException | IOException ignored) {}
            }
        });
    }

    public static void privateSend(MessageVo vo){
        ChatEndpoint endpoint = ChatEndpoint.ONLINE_USERS.get(vo.getReceiver());
        if (endpoint != null){
            try {
                endpoint.send(vo);
            } catch (EncodeException | IOException ignored) {}
        }
    }

    public static void privateSend(Long receiver,MessageVo vo){
        ChatEndpoint endpoint = ChatEndpoint.ONLINE_USERS.get(receiver);
        if (endpoint != null){
            try {
                endpoint.send(vo);
            } catch (EncodeException | IOException ignored) {}
        }
    }
}
